<template>
    <div>
      <button @click="toggleBox">显示盒子</button>
      <hr>
      <transition
       name="fade">
        <div class="box" v-if="show" ref="box"></div>
      </transition>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  
  const show = ref(true);
  const box = ref(null);
  
  const toggleBox = () => {
    show.value = !show.value;
    if(show.value = false){
      box.value.classList.add('.box-leave-active') 
      box.value.classList.remove('.box-enter-active') 
    }
    else{
      box.value.classList.add('.box-enter-active') 
      box.value.classList.remove('.box-leave-active')
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .box {
    width: 200px;
    height: 200px;
    background-color: burlywood;
    opacity: 1;
    transform: translateX(0px);
    transition: opacity 1s ease, transform 1s ease;
    animation: box-enter 1s ease;
  

    &-enter-active {
        animation: box-enter 1s ease;
    }
    &-leave-active {
      animation: box-leave 1s ease;
    }
  }
  
  @keyframes box-enter {
    from {
      opacity: 0;
      transform: translateX(-200px);
    }
  
    to {
      opacity: 1;
      transform: translateX(0px);
    }
  }
  
  @keyframes box-leave {
    from {
      opacity: 1;
      transform: translateX(200px);
    }
  
    to {
      opacity: 0;
      transform: translateX(0px);
    }
  }
  
  </style>
  
  